package com.unohacha.qqj.fzdr.ui.activity.supply;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.qpg.superhttp.SuperHttp;
import com.qpg.superhttp.callback.SimpleCallBack;
import com.qpg.superhttp.request.UploadRequest;
import com.qpg.widget.common.ToastUtil;
import com.unohacha.qqj.fzdr.R;
import com.unohacha.qqj.fzdr.adapter.imgpicker.LeaseImagePickerAdapter;
import com.unohacha.qqj.fzdr.bean.BaseBean;
import com.unohacha.qqj.fzdr.bean.CatData;
import com.unohacha.qqj.fzdr.bean.ImgBean;
import com.unohacha.qqj.fzdr.bean.PublishTip;
import com.unohacha.qqj.fzdr.bean.citybean.TownModle;
import com.unohacha.qqj.fzdr.ui.activity.PubSettlementActivity;
import com.unohacha.qqj.fzdr.util.GlideImageLoaderForPicker;
import com.unohacha.qqj.fzdr.util.Prefer;
import com.unohacha.qqj.fzdr.util.ToastUtils;
import com.unohacha.qqj.mylibrary.base.BaseActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 房屋租赁
 */
public class LeaseOfHousesActivity extends BaseActivity implements LeaseImagePickerAdapter.OnRecyclerViewItemClickListener {
    @BindView(R.id.common_back)
    ImageView commonBack;
    @BindView(R.id.common_title)
    TextView commonTitle;
    @BindView(R.id.et_title)
    EditText etTitle;
    @BindView(R.id.tv_mianji)
    EditText tvMianji;
    @BindView(R.id.et_louceng)
    EditText etLouceng;
    @BindView(R.id.et_cenggao)
    EditText etCenggao;
    @BindView(R.id.et_extra)
    EditText etExtra;
    @BindView(R.id.et_zujin)
    EditText etZujin;
    @BindView(R.id.bt_next)
    Button btNext;
    @BindView(R.id.lly_cate)
    LinearLayout llyCate;
    @BindView(R.id.tv_cate)
    TextView tvCate;
    @BindView(R.id.recycler)
    RecyclerView recyclerView;
    HashMap<String, String> map;
    public static final int IMAGE_ITEM_ADD = -1;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;
    @BindView(R.id.common_right_image)
    ImageView commonRightImage;
    @BindView(R.id.common_right_text)
    TextView commonRightText;
    @BindView(R.id.lly_mianji)
    LinearLayout llyMianji;
    @BindView(R.id.lly_zhiwei)
    LinearLayout llyZhiwei;
    @BindView(R.id.tv_choose_town)
    TextView tvChooseTown;
    @BindView(R.id.lly_xinzhi)
    LinearLayout llyXinzhi;
    @BindView(R.id.ll_choose_town)
    LinearLayout llChooseTown;
    private LeaseImagePickerAdapter imagePickerAdapter;
    public static ArrayList<ImageItem> selImageList; //当前选择的所有图片
    private int maxImgCount = 9;               //允许选择图片最大数
    private String fabricName, fabricId;
    private OptionsPickerView pvCate, pvXinZhi, pvXueLi, pvJingYan, pvQuYu, pvLocation;
    private ArrayList<String> cateList, xueLiList, xinzhiList, jingYanList, quYuList;
    private String type;
    List<CatData> listTwo;
    ArrayList<CatData.Two> listsDetial;
    ArrayList<String> listsCateName;
    ArrayList<String> listTown;
    private String supply_cate_id;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_lease_of_houses;
    }

    @Override
    protected void initData() {
        super.initData();
        listTwo = new ArrayList<>();
        listsCateName = new ArrayList<>();
        listsDetial = new ArrayList<>();
        listTown = new ArrayList<>();
        commonBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        map = new HashMap<>();
        cateList = new ArrayList<>();
        xueLiList = new ArrayList<>();
        xinzhiList = new ArrayList<>();
        jingYanList = new ArrayList<>();
        quYuList = new ArrayList<>();
        fabricName = getIntent().getStringExtra("name");
        fabricId = getIntent().getStringExtra("id");
        type = Prefer.getInstance().getKeyType();
        if (type.equals("1"))
            commonTitle.setText("房屋出租供应");
        else
            commonTitle.setText("房屋出租需求");
        initImagePicker();
        selImageList = new ArrayList<>();
        imagePickerAdapter = new LeaseImagePickerAdapter(this, selImageList, maxImgCount);
        imagePickerAdapter.setOnItemClickListener(this);

        recyclerView.setLayoutManager(new GridLayoutManager(this, 4));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(imagePickerAdapter);

        initOptions();
        getPackerData();
        getTips();
    }

    @OnClick({R.id.lly_cate,R.id.ll_choose_town, R.id.bt_next})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.lly_cate:
                pvCate.show();
                break;
            case R.id.ll_choose_town:
                
                if(listTown.size() < 1){
                    ToastUtils.showT("暂无数据");
                }else{
                    pvLocation.show();
                }
           
                break;
            case R.id.bt_next:
                if (etTitle.getText().toString().length() == 0) {
                    ToastUtil.showCustomToast("请输入标题");
                    return;
                }
                if (tvCate.getText().toString().length() == 0) {
                    ToastUtil.showCustomToast("请选择分类");
                    return;
                }
                map.put("token", Prefer.getInstance().getToken());
                map.put("title", etTitle.getText().toString().trim());
                map.put("supply_cate_id", supply_cate_id);
                map.put("typeid", type);
                map.put("price", "");
                map.put("price_company", "");
                map.put("acreage", tvMianji.getText().toString());
                map.put("acreage_company", "");
                map.put("storey", etLouceng.getText().toString());
                map.put("structure", "");
                map.put("position", "");
                map.put("content", etExtra.getText().toString());
                map.put("story_height", etCenggao.getText().toString());
                map.put("matching", "");
                map.put("town_id", "");
                mSubmit(map);
                break;
        }
    }

    private void initOptions() {
        pvCate = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                tvCate.setText(listsCateName.get(options1));
                supply_cate_id = listsDetial.get(options1).getId() + "";
//                tvAllPrice.setText(listType.get(type).getPrice()*mCount+"");
            }
        }).setContentTextSize(20)//设置滚轮文字大小
                .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                .setSelectOptions(0)//默认选中项
                .setBgColor(Color.WHITE)
                .setTitleBgColor(Color.WHITE)
                .setTitleColor(Color.LTGRAY)
                .setCancelColor(Color.GRAY)
                .setSubmitColor(Color.RED)
                .setSubmitText("完成")
                .setTextColorCenter(Color.BLACK)
                .isCenterLabel(true) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setBackgroundId(0x66000000) //设置外部遮罩颜色
                .build();

        pvLocation = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                tvChooseTown.setText(listTown.get(options1));
//                tvAllPrice.setText(listType.get(type).getPrice()*mCount+"");
            }
        }).setContentTextSize(20)//设置滚轮文字大小
                .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                .setSelectOptions(0)//默认选中项
                .setBgColor(Color.WHITE)
                .setTitleBgColor(Color.WHITE)
                .setTitleColor(Color.LTGRAY)
                .setCancelColor(Color.GRAY)
                .setSubmitColor(Color.RED)
                .setSubmitText("完成")
                .setTextColorCenter(Color.BLACK)
                .isCenterLabel(true) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setBackgroundId(0x66000000) //设置外部遮罩颜色
                .build();

        pvXinZhi = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //    tvXinzhi.setText(xinzhiList.get(options1));
//                type=options1;
//                tvAllPrice.setText(listType.get(type).getPrice()*mCount+"");
            }
        }).setContentTextSize(20)//设置滚轮文字大小
                .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                .setSelectOptions(0)//默认选中项
                .setBgColor(Color.WHITE)
                .setTitleBgColor(Color.WHITE)
                .setTitleColor(Color.LTGRAY)
                .setCancelColor(Color.GRAY)
                .setSubmitColor(Color.RED)
                .setSubmitText("完成")
                .setTextColorCenter(Color.BLACK)
                .isCenterLabel(true) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setBackgroundId(0x66000000) //设置外部遮罩颜色
                .build();

        pvXueLi = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //      tvXueli.setText(xueLiList.get(options1));
//                type=options1;
//                tvAllPrice.setText(listType.get(type).getPrice()*mCount+"");
            }
        }).setContentTextSize(20)//设置滚轮文字大小
                .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                .setSelectOptions(0)//默认选中项
                .setBgColor(Color.WHITE)
                .setTitleBgColor(Color.WHITE)
                .setTitleColor(Color.LTGRAY)
                .setCancelColor(Color.GRAY)
                .setSubmitColor(Color.RED)
                .setSubmitText("完成")
                .setTextColorCenter(Color.BLACK)
                .isCenterLabel(true) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setBackgroundId(0x66000000) //设置外部遮罩颜色
                .build();
        pvJingYan = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //    tvJingyan.setText(jingYanList.get(options1));
//                type=options1;
//                tvAllPrice.setText(listType.get(type).getPrice()*mCount+"");
            }
        }).setContentTextSize(20)//设置滚轮文字大小
                .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                .setSelectOptions(0)//默认选中项
                .setBgColor(Color.WHITE)
                .setTitleBgColor(Color.WHITE)
                .setTitleColor(Color.LTGRAY)
                .setCancelColor(Color.GRAY)
                .setSubmitColor(Color.RED)
                .setSubmitText("完成")
                .setTextColorCenter(Color.BLACK)
                .isCenterLabel(true) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setBackgroundId(0x66000000) //设置外部遮罩颜色
                .build();

        pvQuYu = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //  tvQuyu.setText(quYuList.get(options1));
//                type=options1;
//                tvAllPrice.setText(listType.get(type).getPrice()*mCount+"");
            }
        }).setContentTextSize(20)//设置滚轮文字大小
                .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                .setSelectOptions(0)//默认选中项
                .setBgColor(Color.WHITE)
                .setTitleBgColor(Color.WHITE)
                .setTitleColor(Color.LTGRAY)
                .setCancelColor(Color.GRAY)
                .setSubmitColor(Color.RED)
                .setSubmitText("完成")
                .setTextColorCenter(Color.BLACK)
                .isCenterLabel(true) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setBackgroundId(0x66000000) //设置外部遮罩颜色
                .build();
    }

    private void initImagePicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoaderForPicker());   //设置图片加载器
        imagePicker.setShowCamera(true);                      //显示拍照按钮
        imagePicker.setCrop(false);                           //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
        imagePicker.setSelectLimit(maxImgCount);              //选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);                       //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);                      //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);                         //保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);                         //保存文件的高度。单位像素
    }

    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case IMAGE_ITEM_ADD:
                //打开选择,本次允许选择的数量
                ImagePicker.getInstance().setSelectLimit(maxImgCount - selImageList.size());
                Intent intent1 = new Intent(LeaseOfHousesActivity.this, ImageGridActivity.class);
                startActivityForResult(intent1, REQUEST_CODE_SELECT);

                break;
//            default:
//                //打开预览
//                Intent intentPreview = new Intent(this, ImagePreviewDelActivity.class);
//                intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
//                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
//                intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
//                startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
//                break;
        }
    }

    ArrayList<ImageItem> images = null;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null) {
                    selImageList.addAll(images);
                    imagePickerAdapter.setImages(selImageList);
                }
            }
        } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            //预览图片返回
            if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                if (images != null) {
                    selImageList.clear();
                    selImageList.addAll(images);
                    imagePickerAdapter.setImages(selImageList);
                }
            }
        }
    }

    private void getPackerData() {
        String token = Prefer.getInstance().getToken();
        SuperHttp.post("api/supplyinfo/supplyCate")
                .addParam("token", token)
                .addParam("typeid", "2")
                .request(new SimpleCallBack<BaseBean<List<CatData>>>() {
                    @Override
                    public void onSuccess(BaseBean<List<CatData>> data) {
                        if (data.getCode() == 0) {
                            //   ToastUtil.showCustomToast("暂无数据");
                            return;
                        }
                        listTwo.clear();
                        listTwo.addAll(data.getData());
                        for (int i = 0; i < listTwo.size(); i++) {
                            if (listTwo.get(i).getId() == Integer.valueOf(fabricId)) {
                                listsDetial = new ArrayList<>();
                                listsCateName = new ArrayList<>();
                                listsDetial.addAll(listTwo.get(i).getTwo());
                                for (int j = 0; j < listTwo.get(i).getTwo().size(); j++) {
                                    listsCateName.add(listsDetial.get(j).getName());
                                }

                            }
                        }
                        //   cateId=listsDetial.get(0).getId()+"";
                        tvCate.setText(listsDetial.get(0).getName());
                        supply_cate_id = listsDetial.get(0).getId() + "";
                        pvCate.setPicker(listsCateName);
                        hideLoading();
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        hideLoading();
                    }
                });
        Log.d("townId",Prefer.getInstance().getAreaId());

        SuperHttp.post("api/region/town")
                .addParam("id", Prefer.getInstance().getAreaId())
                .request(new SimpleCallBack<BaseBean<List<TownModle>>>() {
                    @Override
                    public void onSuccess(BaseBean<List<TownModle>> data) {
//                        ToastUtils.showT(data.getData().size()+"....");
                        if (data.getCode() == 0) {
                            //   ToastUtil.showCustomToast("暂无数据");
                            return;
                        }
                        for (int i = 0; i < data.getData().size(); i++) {

                            listTown.addAll(Arrays.asList(data.getData().get(i).getName()));
                            pvLocation.setPicker(listTown);
                        }
                        //   cateId=listsDetial.get(0).getId()+"";

                        hideLoading();
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        ToastUtils.showT(errMsg);
                    }
                });
    }


    private void getTips() {
        String token = Prefer.getInstance().getToken();
        SuperHttp.post("api/supplyinfo/supplyPrompt")
                .addParam("supply_cate_id", fabricId)
                .request(new SimpleCallBack<BaseBean<ArrayList<PublishTip>>>() {
                    @Override
                    public void onSuccess(BaseBean<ArrayList<PublishTip>> data) {
                        if (data.getCode() == 0) {
                            //   ToastUtil.showCustomToast("暂无数据");
                            return;
                        } else if (data.getCode() == 1) {
                            for (int i = 0; i < data.getData().size(); i++) {
                                if (data.getData().get(i).getField_name().equals("期望职位")) {
                                    cateList.addAll(Arrays.asList(data.getData().get(i).getPrompt()));
                                    pvCate.setPicker(cateList);
                                } else if (data.getData().get(i).getField_name().equals("期望薪资")) {
                                    xinzhiList.addAll(Arrays.asList(data.getData().get(i).getPrompt()));
                                    pvXinZhi.setPicker(xinzhiList);

                                } else if (data.getData().get(i).getField_name().equals("学历")) {
                                    xueLiList.addAll(Arrays.asList(data.getData().get(i).getPrompt()));
                                    pvXueLi.setPicker(xueLiList);

                                } else if (data.getData().get(i).getField_name().equals("工作经验")) {
                                    jingYanList.addAll(Arrays.asList(data.getData().get(i).getPrompt()));
                                    pvJingYan.setPicker(jingYanList);

                                } else if (data.getData().get(i).getField_name().equals("期望区域")) {
                                    quYuList.addAll(Arrays.asList(data.getData().get(i).getPrompt()));
                                    pvQuYu.setPicker(quYuList);
                                }
                            }
                        }
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                    }
                });
    }


    private void mSubmit(final HashMap<String, String> map) {
        HashMap<String, String> parmas = new HashMap<>();
        parmas.put("token", Prefer.getInstance().getToken());
        parmas.put("type", "1");
        UploadRequest uploadRequest = SuperHttp.upload("api/filepic/filePic");
        if (images != null) {
            for (int i = 0; i < images.size(); i++) {
                uploadRequest.addImageFile("file" + i, new File(images.get(i).path));
            }
        } else {
            map.put("list_pic", "");
            Intent intent = new Intent(LeaseOfHousesActivity.this, PubSettlementActivity.class);
            intent.putExtra("params", map);
            startActivity(intent);
            finish();
            return;
        }

        uploadRequest.addParams(parmas);

        showLoading();
        uploadRequest.request(new SimpleCallBack<BaseBean<List<ImgBean>>>() {
            @Override
            public void onFail(int errCode, String errMsg) {
                ToastUtil.showCustomToast(errMsg);
                hideLoading();
            }

            @Override
            public void onSuccess(BaseBean<List<ImgBean>> data) {
                StringBuilder stringBuilder = new StringBuilder();
                for (int i = 0; i < data.getData().size(); i++) {
                    stringBuilder.append(data.getData().get(i).getId() + ",");
                }
                map.put("list_pic", stringBuilder.toString());
                Intent intent = new Intent(LeaseOfHousesActivity.this, PubSettlementActivity.class);
                intent.putExtra("params", map);
                startActivity(intent);

                hideLoading();
                finish();
            }
        });
    }

}
